﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Linq.Dynamic.Core;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using PMS.XCMG.Entity;
using PMS.XCMG.IBusiness;
using PMS.XCMG.Util;
using PMS.XCMG.Models;

namespace PMS.XCMG.Business
{
    public class StorageAreaBusiness : BusRepository<StorageArea>, IStorageAreaBusiness, IScopedDependency
    {
        private IServiceProvider SvcProvider { get; set; }
        public StorageAreaBusiness(GDbContext context, IServiceProvider svcProvider)
            : base(context)
        {
            this.SvcProvider = svcProvider;
        }

        public async Task<PageResult<StorageArea>> GetPageResultAsync(PageInput<StorageAreaQM> query)
        {
            var queryable = this.GetQueryable(true);
            queryable = queryable.Include(i => i.Materiel);

            var search = query.Search;
            if (!search.Keyword.IsNullOrEmpty())
                queryable = queryable.Where(w => w.Name.Contains(search.Keyword) || w.Code.Contains(search.Keyword));


            var result = await this.GetPageResultAsync(queryable, query);
            if (!search.Id.IsNullOrEmpty())
            {
                if (!result.Data.Any(w => w.Id == search.Id))
                {
                    var idOne = await this.GetQueryable(true).SingleOrDefaultAsync(w => w.Id == search.Id);
                    result.Data.Add(idOne);
                    result.Total += 1;
                }
            }
            return result;
        }
    }
}
